<template>
  <base-container>
    <template #title>
      <table-toolbar>
        <template #bar-left>
          <div @click="handleBack" class="cursor-pointer flex items-center">
            <arrow-left-outlined class="inline-block leading-0 ft-14 mr-2" />
            <p class="mb-0 font-bold ft-16">{{ word }}（{{ PlatformKeyMap[clientType] }}）</p>
          </div>
        </template>
      </table-toolbar>
    </template>
    <a-spin :spinning="loading">
      <a-form layout="vertical" :model="formFields" :rules="formRules" ref="FormRef">
        <a-form-item label="落地页" class="w-600" name="destinationUrl">
          <a-input placeholder="请输入落地页" v-model:value="formFields.destinationUrl"></a-input>
        </a-form-item>
        <a-form-item label="标题" class="w-600" name="title">
          <a-input placeholder="请输入标题" v-model:value="formFields.title"></a-input>
        </a-form-item>
        <a-form-item label="内容" class="w-600" name="content">
          <a-textarea
            placeholder="请输入内容"
            v-model:value="formFields.content"
            :auto-size="{ minRows: 5, maxRows: 5 }"
          />
        </a-form-item>
        <table-toolbar title="投放物料设置" />
        <material-example @on-use="handleUseExample" />
        <divider />
        <div v-if="showCreative || isGift">
          <template v-if="showPcCreative">
            <a-row :gutter="30">
              <a-col :span="12" class="creative">
                <table-toolbar title="创意配图（PC端）" class="creative__picture" />
                <div>
                  <template v-if="isGift && pcImgNum && pcImgNum > 1">
                    <a-form-item label="设备名称" class="w-600" name="deviceName">
                      <a-input
                        :readonly="isFirst === isFirstEnum.Other"
                        placeholder="请输入设备名称"
                        v-model:value="formFields.deviceName"
                      ></a-input>
                    </a-form-item>
                    <a-form-item label="详情" class="w-600" name="details">
                      <a-input
                        :readonly="isFirst === isFirstEnum.Other"
                        placeholder="请输入详情"
                        v-model:value="formFields.details"
                      ></a-input>
                    </a-form-item>
                    <a-form-item label="服务" class="w-600" name="service">
                      <a-input
                        :readonly="isFirst === isFirstEnum.Other"
                        placeholder="请输入服务"
                        v-model:value="formFields.service"
                      ></a-input>
                    </a-form-item>
                    <a-form-item label="特色" class="w-600" name="feature">
                      <a-input
                        :readonly="isFirst === isFirstEnum.Other"
                        placeholder="请输入特色"
                        v-model:value="formFields.feature"
                      ></a-input>
                    </a-form-item>
                  </template>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="30">
              <a-col :span="12" class="creative">
                <promotion-goods
                  :add-creative="addCreative"
                  :client-type="PlatformEnum.PC"
                  :isGift="isGift"
                  :word="word"
                  :isFirst="isFirst"
                  :show-require-pic-rule="showPcCreativeRule"
                  v-model:active-key="pcActiveKey"
                  v-model:goods="formFields.pcGoods"
                />
              </a-col>
              <a-col :span="12" v-show="showPcCreativeRule">
                <table-toolbar title="展现样式" />
                <PromotionExample :client-type="PlatformEnum.PC" :form-fields="formFields" :isGift="isGift" />
              </a-col>
            </a-row>
            <divider class="line" />
          </template>
          <template v-if="showWapCreative">
            <a-row :gutter="30">
              <a-col :span="12" class="creative">
                <table-toolbar title="创意配图（移动端）" class="creative__picture" />
                <promotion-goods
                  :add-creative="addCreative"
                  :client-type="PlatformEnum.MOBILE"
                  :word="word"
                  :isGift="isGift"
                  :isFirst="isFirst"
                  :show-require-pic-rule="showWapCreativeRule"
                  v-model:active-key="wapActiveKey"
                  v-model:goods="formFields.wapGoods"
                />
              </a-col>
              <a-col :span="12" v-show="showWapCreativeRule">
                <table-toolbar title="展现样式" />
                <PromotionExample :client-type="PlatformEnum.MOBILE" :form-fields="formFields" :isGift="isGift" />
              </a-col>
            </a-row>
            <divider />
          </template>
        </div>
        <div v-if="batchVisible || isGift" class="bottom-20">
          <table-toolbar title="批量应用" />
          <promotion-batcher
            v-model:selected-keys="batchKeys"
            v-model:show-batcher="showBatcher"
            :raw-table-data="creatives"
            :table-data="creativesExceptCurrent"
            :batch-submitter="submitCreative"
            :match-campaign-id="matchCampaignId"
            :order-word-id="orderWordId"
            :productId="currentInfo.productId"
            :clientType="clientType"
          />
        </div>

        <a-form-item class="mb-0">
          <a-button type="primary" :loading="submitting" @click="handleCreative">提交创意</a-button>
          <a-button class="ml-2 mr-2" @click="router.go(-1)">返回</a-button>
          <a-button danger @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </base-container>
</template>

<script lang="ts" setup name="PromotionCreative">
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import BaseContainer from '@/components/base-container/index.vue'
import { debounce, isNil, last, omit, zipWith } from 'lodash-es'
import TableToolbar from '@/components/table-toolbar/index.vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import getSingleWordCreative from '@/services/promotion/getSingleWordCreative'
import { usePromotionStore, isFirstEnum } from '@/store/usePromotionStore'
import { type FormInstance, message, Modal } from 'ant-design-vue'
import updatePromotionCreative, { type Goods } from '@/services/promotion/updatePromotionCreative'
import type { ValidateErrorEntity } from 'ant-design-vue/lib/form/interface'
import is from '@/utils/is'
import { calMode, type GoodsFields, type PromotionFields, type TargetKeyword } from '@/views/promotion/interface'
import MaterialExample from '@/views/promotion/components/MaterialExample.vue'
import {
  byteLength,
  byteLengthSplit,
  emojiMatcher,
  getMime,
  makeShortId,
  picSrcToBase64,
  containsBraces,
  validParentheses
} from '@/utils'
import type { Rule } from 'ant-design-vue/es/form'
import PromotionExample from '@/views/promotion/components/PromotionExample.vue'
import Divider from '@/components/divider/index.vue'
import checkPromotionUrl from '@/services/promotion/checkPromotionUrl'
import PromotionGoods from '@/views/promotion/components/PromotionGoods.vue'
import PromotionBatcher from '@/views/promotion/components/PromotionBatcher.vue'
import { Mode } from '@/core/interfaces/common'
import { PlatformEnum } from '@/core/enums/platform'
import { CreativePictureEnum, WordTypeEnum } from '@/core/enums/type'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { storeToRefs } from 'pinia'
import { isDevOrDevelopment } from '@/shared/env'
import { ProductEnum } from '@/core/enums/platform'

const router = useRouter()
const FormRef = ref<FormInstance>()

const promotionStore = usePromotionStore()
const {
  currentPromotionData: currentInfo,
  currentOrderWordId,
  currentCreative,
  creatives,
  creativesExceptCurrent,
  isFirstCreative,
  isWapFirstCreative
} = storeToRefs(promotionStore)

const {
  pcImgNum,
  ydImgNum,
  wapCampaignId,
  pcCampaignId,
  pcWapCampaignId,
  hasCreativePic: hasCreativePicture
} = toRefs(currentInfo.value)
const { id, orderWordId, word, clientType, type, isFirst } = toRefs(currentCreative.value) // 购买配图的订单也会有此逻辑吗？
console.log(currentInfo.value.productId, '')

const [, fetchSingleWordCreative, loading] = getSingleWordCreative()
const [, fetchPromotionCreative, submitting] = updatePromotionCreative()
const [, fetchPromotionByGet] = checkPromotionUrl()

const defaultFormFields = () => ({
  destinationUrl: '',
  title: `{${word?.value}}`,
  content: '',
  wapGoods: [],
  pcGoods: [],
  groupId: undefined,
  details: undefined,
  feature: undefined,
  deviceName: undefined,
  service: undefined,
  bxAbcWordCode: 0
})
const formFields = reactive<PromotionFields>(defaultFormFields())

// 是否主词
const shouldSold = computed(() => {
  return type?.value === WordTypeEnum.sold
})

// 是否有配图
const showCreative = computed(() => {
  return hasCreativePicture?.value === CreativePictureEnum.yes
  // return shouldSold.value && hasCreativePicture?.value === CreativePictureEnum.yes
})

// 是否为赠送的配图
const isGift = computed(() => {
  return !showCreative.value && shouldSold.value && (pcImgNum?.value != 0 || ydImgNum?.value != 0)
})

const formRules = reactive({
  destinationUrl: [
    {
      required: true,
      trigger: ['change', 'blur'],
      pattern:
        (currentInfo.value.productId === 9 && currentInfo.value.serviceUserName === null) ||
        ((currentInfo.value.productId === 7 || currentInfo.value.productId === 10) &&
          currentInfo.value.thType === 1 &&
          currentInfo.value.serviceUserName === null)
          ? /^(https:\/\/)([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)*(shop\.baixing\.cn|mvpb2b\.baixing\.cn|mvp\.baixing\.cn)\/?/
          : /^(https:\/\/)([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)*(shop\.baixing\.com|shop\.e-baixing\.com|vip\.e-baixing\.com|mvp\.baixing\.cn|mvpb2b\.baixing\.cn|shop\.baixing\.cn|pz\.baixing\.cn|mvp\.baixing\.cn)\/?/,
      validator: debounce(checkDestinationUrl, 800)
    }
  ],
  title: [
    {
      required: true,
      trigger: ['change', 'blur'],
      validator: checkTitle
    }
  ],
  content: [
    {
      required: true,
      trigger: ['change', 'blur'],
      validator: checkContent
    }
  ],
  deviceName: [
    {
      required: isGift,
      trigger: ['change', 'blur'],
      validator: checkStats
    }
  ],
  details: [
    {
      required: isGift,
      trigger: ['change', 'blur'],
      validator: checkStats
    }
  ],
  service: [
    {
      required: isGift,
      trigger: ['change', 'blur'],
      validator: checkStats
    }
  ],
  feature: [
    {
      required: isGift,
      trigger: ['change', 'blur'],
      validator: checkStats
    }
  ]
})

const batchKeys = ref<number[]>([])
const showBatcher = ref(false)

const mode = computed(() => {
  return calMode(id?.value)
})

const batchVisible = computed(() => {
  // 关键词列表数量大于1个且当前关键词不是赠词
  // 赠词不显示批量应用
  return creativesExceptCurrent.value.length > 0 && shouldSold.value
})

const showPcCreative = computed(() => {
  return (clientType?.value === PlatformEnum.Platform || clientType?.value === PlatformEnum.PC) && shouldSold.value
})

const showWapCreative = computed(() => {
  return (clientType?.value === PlatformEnum.Platform || clientType?.value === PlatformEnum.MOBILE) && shouldSold.value
})

const showPcCreativeRule = computed(() => {
  return formFields.pcGoods.some((g) => g.fileList!.length > 0 || g.name || g.info)
})

const showWapCreativeRule = computed(() => {
  if (clientType?.value === PlatformEnum.Platform) {
    return showPcCreativeRule.value || formFields.wapGoods.some((g) => g.fileList!.length > 0)
  }
  return formFields.wapGoods.some((g) => g.fileList!.length > 0)
})

const pcActiveKey = ref(formFields.pcGoods[0]?.key ?? 1)
const wapActiveKey = ref(formFields.wapGoods[0]?.key ?? 1)

async function checkDestinationUrl(_rule: Rule, value: string) {
  const min = 1
  const max = 2048

  if (!value) {
    return Promise.reject(`请输入落地页地址，长度须控制在${min}到${max}字节内`)
  }

  const len = byteLength(value)
  if (min - len > 0) {
    return Promise.reject(`落地页地址还差${Math.abs(min - len)}个字节`)
  }

  if (max - len < 0) {
    return Promise.reject(`落地页地址超出${Math.abs(max - len)}个字节`)
  }

  if (
    (currentInfo.value.productId === 9 && currentInfo.value.serviceUserName === null) ||
    ((currentInfo.value.productId === 7 || currentInfo.value.productId === 10) &&
      currentInfo.value.thType === 1 &&
      currentInfo.value.serviceUserName === null)
  ) {
    if (!_rule.pattern?.test(value)) {
      return Promise.reject(
        'abc词默认投放在百姓账户，请输入正确的百姓店铺链接，例如：shop.baixing.cn或mvpb2b.baixing.cn或mvp.baixing.cn'
      )
    }
    return Promise.resolve()
  }

  if (
    currentInfo.value.productId === ProductEnum.BWYXB ||
    currentInfo.value.productId === ProductEnum.CBYXB ||
    (currentInfo.value.productId === ProductEnum.CBTEH && currentInfo.value.thType === 0) ||
    currentInfo.value.productId === ProductEnum.BWSDYXB
  ) {
    const reg = /^https:\/\/.*e-baixing\.com/
    if (!reg.test(value)) {
      return Promise.reject('请输入正确的链接，例如：https://xxx.e-baixing.com/xxx（xxx为代替字符）')
    }
    return Promise.resolve()
  } else {
    if (!_rule.pattern?.test(value)) {
      return Promise.reject('请输入正确的落地页地址，以https://mvp.baixing.cn为例')
    }
  }

  const destinationUrl = formFields.destinationUrl.replace(/\.baixing\.com/, '.baixing.cn')
  const [err] = await fetchPromotionByGet({
    serviceUserName: currentInfo.value?.serviceUserName ?? '',
    destinationUrl
  })

  if (!err) {
    return Promise.resolve()
  } else {
    return Promise.reject(err.message)
  }
}

function checkTitle(_: any, value: string) {
  const min = 9
  const max = 50

  if (emojiMatcher(value)) {
    return Promise.reject('文案中存在如：表情等非法字符')
  }

  if (!validParentheses(value)) {
    return Promise.reject('通配符匹配失败，请合理使用通配符。')
  }

  if (!value) {
    return Promise.reject(`请输入标题，长度须控制在${min}到${max}字节内`)
  }

  const len = byteLength(value)
  if (min - len > 0) {
    return Promise.reject(`标题还差${Math.abs(min - len)}个字节`)
  }
  const regex = /\{.*\}/g
  if (!regex.test(value)) {
    return Promise.reject('通配符{***}为必加创意格式，不加展现率较差，建议固定为客户购买的关键词。')
  }
  if (max - len < 0) {
    return Promise.reject(`标题超出${Math.abs(max - len)}个字节`)
  }

  return Promise.resolve()
}

function checkContent(_: any, value: string) {
  const min = 9
  const max = 159

  if (emojiMatcher(value)) {
    return Promise.reject('文案中存在如：表情等非法字符')
  }

  if (!validParentheses(value)) {
    return Promise.reject('通配符匹配失败，请合理使用通配符。')
  }

  if (!value) {
    return Promise.reject(`请输入内容，长度须控制在${min}到${max}字节内`)
  }

  const len = byteLength(value)
  if (min - len > 0) {
    return Promise.reject(`内容还差${Math.abs(min - len)}个字节`)
  }

  if (max - len < 0) {
    return Promise.reject(`内容超出${Math.abs(max - len)}个字节`)
  }

  return Promise.resolve()
}

function checkStats(_: any, value: string) {
  const min = 1
  const max = 23

  if (!value) {
    return Promise.reject(`请输入内容，长度须控制在${min}到${max}字节内`)
  }

  const len = byteLength(value)
  if (min - len > 0) {
    return Promise.reject(`内容还差${Math.abs(min - len)}个字节`)
  }

  if (max - len < 0) {
    return Promise.reject(`内容超出${Math.abs(max - len)}个字节`)
  }

  return Promise.resolve()
}

function handleBack() {
  router.go(-1)
}

function matchCampaignId(clientType?: PlatformEnum) {
  switch (clientType) {
    case PlatformEnum.PC:
      return pcCampaignId?.value
    case PlatformEnum.MOBILE:
      return wapCampaignId?.value
    case PlatformEnum.Platform:
      return pcWapCampaignId?.value
  }
}

const campaignId = computed(() => {
  return matchCampaignId(clientType?.value)
})

// 标题可以输入大括号语法，当匹配到括号内为关键词名称，则后续批量应用关键词，若没匹配成功，则用括号内的文字
function normalizeStr(str: string, word?: string, targetKeyword?: string) {
  return str.replace(/\{(.+?)\}/g, (match, offset) => {
    if (offset === word) {
      return `{${targetKeyword || word}}`
    }
    return match
  })
}

async function submitCreative(targetKeyword?: TargetKeyword) {
  const title = normalizeStr(formFields.title, word?.value, targetKeyword?.word)
  const content = normalizeStr(formFields.content, word?.value, targetKeyword?.word)

  try {
    await checkTitle(null, title)
    await checkContent(null, content)
    // 百度内容输入框有两个，每个输入框最大输入长度为80个字符，所以需要分割成两个字段提交
    const [description1, description2] = byteLengthSplit(content).map((desc) =>
      desc.replace(/，/g, ',').replace(/。/g, '.')
    ) // 中文逗号、句号转英文

    // 对 title 也进行中文标点转英文标点
    const processedTitle = title.replace(/，/g, ',').replace(/。/g, '.')

    const map = new Map()
    map.set('设备名称', formFields.deviceName)
    map.set('服务', formFields.service)
    map.set('特色', formFields.feature)
    map.set('详情', formFields.details)
    const myList = Array.from(map.entries()).map(([key, value]) => ({ key, value }))

    if (isGift.value) {
      formFields.pcGoods = formFields.pcGoods.map((item) => {
        return {
          ...item,
          selectLists: myList,
          deviceName: formFields.deviceName,
          service: formFields.service,
          feature: formFields.feature,
          details: formFields.details
        }
      })
    }

    return await fetchPromotionCreative(
      {
        ...omit(formFields, ['content', 'details', 'feature', 'deviceName', 'service']),
        title: processedTitle, // 使用处理后的 title
        description1,
        description2,
        orderId: currentInfo.value.orderId,
        destinationUrl: formFields.destinationUrl.replace(/\.baixing\.com/, '.baixing.cn'),
        // targetKeyword是因为有批量应用所以增加的形参
        // 如果targetKeyword不存在则提交当前关键词的word和orderWordId
        word: targetKeyword?.word ?? word?.value,
        orderWordId: targetKeyword?.orderWordId ?? orderWordId?.value,
        campaignId: targetKeyword?.campaignId ?? campaignId.value,
        creativeId: targetKeyword?.creativeId ?? formFields.creativeId,
        clientType: targetKeyword?.clientType ?? currentCreative?.value.clientType,
        id: targetKeyword?.id ?? formFields.id,
        groupId: targetKeyword?.groupId ?? formFields.groupId,
        serviceUserName: currentInfo.value.serviceUserName,
        // 筛选出填了商品图片或者商品名称的goods
        pcGoods: zipWith(
          formFields.pcGoods
            .filter((item) => item.imageContent || item.name)
            .map((item) => ({
              ...omit(item, ['cropper', 'fileList']),
              clientType: PlatformEnum.PC
            })),
          targetKeyword?.pcGoods,
          goodsMerger(targetKeyword?.orderWordId ?? orderWordId?.value)
        ),
        // 筛选出填了商品图片或者商品名称的goods
        wapGoods: zipWith(
          formFields.wapGoods
            .filter((item) => item.imageContent || item.name)
            .map((item) => ({
              ...omit(item, ['cropper', 'fileList']),
              clientType: PlatformEnum.MOBILE
            })),
          targetKeyword?.wapGoods,
          goodsMerger(targetKeyword?.orderWordId ?? orderWordId?.value)
        )
      },
      targetKeyword?.mode ?? mode.value
    )
  } catch (e: any) {
    return Promise.resolve([new Error(e), null])
  }
}

const goodsMerger =
  (orderWordId: TargetKeyword['orderWordId'] = 0) =>
  (a: Goods, b: Goods) => {
    if (isNil(b)) {
      return {
        ...a,
        orderWordId
      }
    } else {
      return {
        ...a,
        id: b.id,
        orderWordId: b.orderWordId,
        creativeGroupId: b.creativeGroupId,
        creativeGroupName: b.creativeGroupName
      }
    }
  }

function handleCreative() {
  FormRef.value
    ?.validate()
    .then(async () => {
      // if (isGift.value && shouldSold.value && creativesExceptCurrent.value.length) {
      //   batchKeys.value = creativesExceptCurrent.value.filter((item) => item.type === 0).map((item) => item.orderWordId)
      // }

      if (batchKeys.value.length > 0) {
        showBatcher.value = true
        return
      }

      Modal.confirm({
        title: '提示',
        content: '是否确定提交创意？',
        async onOk() {
          const [err, res] = await submitCreative()

          if (!err) {
            message.success((res as any)?.data?.msg)
            handleBack()
          } else {
            message.error(err.message || '提交失败，请稍候再试')
          }
        }
      })
    })
    .catch(({ errorFields }: ValidateErrorEntity) => {
      if (is.array(errorFields[0]?.name)) {
        message.error(errorFields[0].errors)
        const validKey = errorFields[0].name[0]
        const validIndex = errorFields[0].name[1] as number

        if (validKey === 'pcGoods') {
          pcActiveKey.value = formFields.pcGoods[validIndex].key
        }

        if (validKey === 'wapGoods') {
          wapActiveKey.value = formFields.wapGoods[validIndex].key
        }
      }
    })
}

function handleReset() {
  Object.assign(formFields, defaultFormFields())
  batchKeys.value = []

  loadSingleWordCreative()
}

function handleUseExample(val: { title: string; content: string }) {
  formFields.title = val.title
  formFields.content = val.content
}

function makeCreative(len: number = 1) {
  return {
    title: `商品${len}`,
    key: len,
    info: '',
    name: '',
    orderWordId: orderWordId?.value ?? 0,
    pictureURL: '',
    imageContent: '',
    pictureName: '',
    fileList: [],
    closable: false,
    cropper: {
      show: false,
      file: undefined
    }
  }
}

function addCreative(goodsModel: GoodsFields[], count: number = 1) {
  for (let i = 0; i < count; i++) {
    const len = (last(goodsModel)?.key ?? 0) + 1
    goodsModel.push(makeCreative(len))
  }
}

async function loadSingleWordCreative() {
  if (showCreative.value && shouldSold.value) {
    switch (clientType?.value) {
      case PlatformEnum.Platform: {
        addCreative(formFields.pcGoods, 4)
        addCreative(formFields.wapGoods, 3)
        break
      }
      case PlatformEnum.MOBILE: {
        addCreative(formFields.wapGoods, 3)
        break
      }
      case PlatformEnum.PC: {
        addCreative(formFields.pcGoods, 4)
        break
      }
    }
  } else if (isGift.value) {
    switch (clientType?.value) {
      case PlatformEnum.Platform: {
        addCreative(formFields.pcGoods, pcImgNum?.value)
        addCreative(formFields.wapGoods, ydImgNum?.value)
        break
      }
      case PlatformEnum.MOBILE: {
        addCreative(formFields.wapGoods, ydImgNum?.value)
        break
      }
      case PlatformEnum.PC: {
        addCreative(formFields.pcGoods, pcImgNum?.value)
        break
      }
    }
  }

  if (mode.value === Mode.edit) {
    const [err, res] = await fetchSingleWordCreative({ id: id!.value! })
    const data = res.data.data

    if (!err) {
      formFields.id = data.id
      formFields.creativeId = data.creativeId
      formFields.destinationUrl = data.destinationUrl
      formFields.title = data.title
      formFields.content = data.content
      formFields.groupId = data.groupId
      formFields.bxAbcWordCode = data.bxAbcWordCode

      if (isGift.value && isFirst?.value === isFirstEnum.Other) {
        formFields.details = isFirstCreative.value.pcGoods?.length
          ? isFirstCreative.value.pcGoods[0].details
          : undefined
        formFields.feature = isFirstCreative.value.pcGoods?.length
          ? isFirstCreative.value.pcGoods[0].feature
          : undefined
        formFields.service = isFirstCreative.value.pcGoods?.length
          ? isFirstCreative.value.pcGoods[0].service
          : undefined
        formFields.deviceName = isFirstCreative.value.pcGoods?.length
          ? isFirstCreative.value.pcGoods[0].deviceName
          : undefined
        //isFirstCreative默认取PC端第一条，isWapFirstCreative取移动端第一条
        if (isFirstCreative.value.pcGoods?.length && (clientType.value === 0 || clientType.value === 2)) {
          formFields.pcGoods = await Promise.all(isFirstCreative.value.pcGoods.map(makeGoodsFields))
        }
        if (isWapFirstCreative.value.wapGoods?.length && (clientType.value === 1 || clientType.value === 2)) {
          formFields.wapGoods = await Promise.all(isWapFirstCreative.value.wapGoods.map(makeGoodsFields))
        }
      } else {
        formFields.details = data.pcGoods.length ? data.pcGoods[0].details : undefined
        formFields.feature = data.pcGoods.length ? data.pcGoods[0].feature : undefined
        formFields.service = data.pcGoods.length ? data.pcGoods[0].service : undefined
        formFields.deviceName = data.pcGoods.length ? data.pcGoods[0].deviceName : undefined
        if (data.pcGoods.length && (clientType.value === 0 || clientType.value === 2)) {
          formFields.pcGoods = await Promise.all(data.pcGoods.map(makeGoodsFields))
        }
        if (data.wapGoods.length && (clientType.value === 1 || clientType.value === 2)) {
          formFields.wapGoods = await Promise.all(data.wapGoods.map(makeGoodsFields))
        }
      }
    }
  } else {
    if (isGift.value && isFirst?.value === isFirstEnum.Other) {
      formFields.details = isFirstCreative.value.pcGoods?.length ? isFirstCreative.value.pcGoods[0].details : undefined
      formFields.feature = isFirstCreative.value.pcGoods?.length ? isFirstCreative.value.pcGoods[0].feature : undefined
      formFields.service = isFirstCreative.value.pcGoods?.length ? isFirstCreative.value.pcGoods[0].service : undefined
      formFields.deviceName = isFirstCreative.value.pcGoods?.length
        ? isFirstCreative.value.pcGoods[0].deviceName
        : undefined

      if (isFirstCreative.value.pcGoods?.length && (clientType.value === 0 || clientType.value === 2)) {
        formFields.pcGoods = await Promise.all(isFirstCreative.value.pcGoods.map(makeGoodsFields))
      }
      if (isWapFirstCreative.value.wapGoods?.length && (clientType.value === 1 || clientType.value === 2)) {
        formFields.wapGoods = await Promise.all(isWapFirstCreative.value.wapGoods.map(makeGoodsFields))
      }
      //兼容标王标品
      if (currentInfo.value.productId === ProductEnum.BWSD || currentInfo.value.productId === ProductEnum.BWSDYXB) {
        const obj = creatives.value.find((item) => item.isFirst === 1 && item.clientType === 1)
        if (obj?.wapGoods.length) {
          formFields.wapGoods = await Promise.all(obj?.wapGoods.map(makeGoodsFields))
        }
      }
    }
  }
}

/**
 * 根据图片的url转换对应的base64值
 * @param { String } imageUrl
 * @returns base64取值
 */
async function urlToBase64(imageUrl) {
  return new Promise((resolve, reject) => {
    let canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    let img = new Image()
    img.crossOrigin = 'Anonymous' // 解决Canvas.toDataURL 跨域问题
    img.src = imageUrl

    img.onload = function () {
      canvas.height = img.height
      canvas.width = img.width
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, img.width, img.height)
      ctx.drawImage(img, 0, 0)

      const dataURL = canvas.toDataURL('image/png')
      const base64String = dataURL.split(',')[1]
      resolve(base64String)
      canvas = null
      img = null
    }

    img.onerror = function () {
      reject(new Error('Could not load image at ' + imageUrl))
    }
  })
}

async function makeGoodsFields(item: Goods, i: number) {
  const imageContent = await urlToBase64(item.pictureURL)
  const pictureName = `${makeShortId()}${word?.value ?? ''.slice(0, 3)}.${getMime(item.pictureName)}`

  return Object.assign(makeCreative(), {
    ...item,
    pictureName,
    title: `商品${i + 1}`,
    key: i + 1,
    imageContent: imageContent,
    fileList: [
      {
        name: pictureName,
        status: 'done',
        url: item.pictureURL,
        preview: imageContent
      }
    ]
  })
}
const productId = ref(0)
onMounted(() => {
  productId.value = localStorage.getItem('productId')
  if (isNil(currentOrderWordId.value)) {
    router.replace({
      name: 'promotion'
    })
  } else {
    loadSingleWordCreative()
  }
})
</script>

<style lang="scss" scoped>
.text-30 {
  font-size: 30px;
}

.top-20 {
  margin-top: 20px;
}

.bottom-20 {
  margin-bottom: 20px;
}

.w-600 {
  max-width: 600px;
}

.creative {
  &__picture {
    margin-top: 0;
    padding-top: 0;
    height: 38px;
  }
}

.line {
  margin-top: 0;
}
</style>
